import axios from 'axios'

// 获取微信配置
export const getWechatConfig = async () => {
  try {
    const response = await axios.get('/api/wechat/config')
    return response.data
  } catch (error) {
    console.error('获取微信配置失败:', error)
    throw error
  }
}

// 初始化微信SDK
export const initWechatSDK = async () => {
  const config = await getWechatConfig()

  return new Promise(resolve => {
    window.wx.config({
      debug: process.env.NODE_ENV === 'development',
      appId: config.appId,
      timestamp: config.timestamp,
      nonceStr: config.nonceStr,
      signature: config.signature,
      jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'scanQRCode'],
    })

    window.wx.ready(() => {
      resolve(true)
    })

    window.wx.error(res => {
      console.error('微信SDK初始化失败:', res)
      resolve(false)
    })
  })
}

// 微信授权登录
export const wechatAuthLogin = (scope = 'snsapi_userinfo') => {
  return new Promise((resolve, reject) => {
    window.wx.getNetworkType({
      success: async () => {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appId}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=${scope}&state=wechat_auth#wechat_redirect`
      },
      fail: err => {
        reject(new Error('微信环境检测失败'))
      },
    })
  })
}

// 处理微信授权回调
export const handleWechatCallback = async code => {
  try {
    const response = await axios.post('/api/wechat/auth', { code })
    return response.data
  } catch (error) {
    console.error('微信授权失败:', error)
    throw error
  }
}

// 绑定微信账号
export const bindWechatAccount = async (openid, userId) => {
  try {
    const response = await axios.post('/api/wechat/bind', { openid, userId })
    return response.data
  } catch (error) {
    console.error('绑定微信账号失败:', error)
    throw error
  }
}
